package com.sxd.bill.rela.util;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.sxd.bill.common.enums.LabelNameEnum;
import com.sxd.bill.common.item.LabelItem;
import com.sxd.bill.common.item.TextLabelItem;

public class SimpleRecognizer {

    public static String recognizeRootTradingDirection(TextLabelItem textLabelItem) {
        String text = textLabelItem.getText();
        List<LabelItem> labelItems = textLabelItem.getLabelItems();

        Pattern pattern = Pattern.compile("(?<!卖|买|托)(?<TRADE>买断|买断|出|收)[】：:]$");

        Matcher matcher = pattern.matcher(text.trim());

        if (labelItems.isEmpty() && text.trim().length() <= 5 && matcher.find()) {
            return matcher.group("TRADE");
        } else {
            return null;
        }
    }

    /**
     * 识别“交易方向”
     * 
     * @param textLabelItem
     * @return
     */
    public static String recognizeTradingDirection(TextLabelItem textLabelItem) {
        String text = textLabelItem.getText();

        Pattern pattern = Pattern.compile("[^：:、\\d]{0,2}(?<!卖|买|托)(?<TRADE>出|收|卖断|买断|买|卖)\\D{0,2}");
        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {
            return matcher.group("TRADE");
        } else {
            return null;
        }
    }

    /**
     * 识别提取"发布者所属机构"
     * 
     * @param textLabelItem
     * @return
     */
    public static String recognizePublisherOrg(TextLabelItem textLabelItem) {
        List<LabelItem> labelItems = textLabelItem.getLabelItems();
        // 选择“发布者所属机构”标签对应的实体
        List<String> orgs = labelItems.stream()
                .filter(item -> item.getLabelName().equals(LabelNameEnum.PUB_ORG))
                .map(item -> (String) item.getLabelEntity())
                .collect(Collectors.toList());

        return orgs.isEmpty() ? null : orgs.get(orgs.size() - 1); // 取最后一个发布者所属机构
    }

    /**
     * 识别手机号码
     * 
     * @param textLabelItem
     * @return
     */
    public static String recognizePhoneNum(TextLabelItem textLabelItem) {
        String text = textLabelItem.getText();
        Pattern pattern = Pattern.compile("\\D(?<PHONE>1[34578]\\d{9})\\D");
        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {
            return matcher.group("PHONE");
        } else {
            return null;
        }
    }

}
